package com.ywu.role.standard.service;

import com.ywu.boot.context.YwuContext;
import com.ywu.boot.context.YwuContextHolder;
import com.ywu.boot.utils.RedisUtils;
import com.ywu.common.gson.GsonUtils;
import com.ywu.common.result.CommonResult;
import com.ywu.common.utils.TimerIdGenerateUtil;
import com.ywu.role.standard.data.MenuRoleAuthRepository;
import com.ywu.role.standard.dto.MenuRoleAuthDto;
import com.ywu.role.standard.dto.MenuRoleAuthPermissionDto;
import com.ywu.role.standard.entity.MenuRoleAuthEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @ClassName MenuRoleAuthService
 * @Description TODO
 * @Author GroundDemo
 * @Date 2024/5/29 21:38
 * @Version 1.0
 **/
@Service
@Slf4j
public class MenuRoleAuthService {
    @Autowired
    private MenuRoleAuthRepository menuRoleAuthRepository;

    private static final String YWU_MENU_PERMISSION_REDIS_KEY = "YWU_MENU_PERMISSION:menu";

    /**
     * @Author GroundDemo
     * @Description 查询菜单关联的角色
     * @Date 22:02 2024/3/9
     * @Param [menuRoleAuthDto]
     * @return com.ywu.common.result.CommonResult<java.lang.Object>
     **/
    public CommonResult<Object> queryMenuRoleInfo(MenuRoleAuthDto menuRoleAuthDto) {
        // 判断缓存是否存在
        String redisInfo = RedisUtils.getHashByKey(YWU_MENU_PERMISSION_REDIS_KEY, String.valueOf(menuRoleAuthDto.getMenuId()));
        if (Objects.nonNull(redisInfo)) {
            log.debug("query menu role info using redis cache");
            List<MenuRoleAuthEntity> menuRoleAuthEntities = GsonUtils.deserializeList(redisInfo, MenuRoleAuthEntity.class);
            return CommonResult.success(menuRoleAuthEntities);
        }
        List<MenuRoleAuthEntity> menuRoleAuthEntities = menuRoleAuthRepository.queryMenuRoleInfo(menuRoleAuthDto);
        List<MenuRoleAuthEntity> res = new ArrayList<>();
        if (Objects.isNull(menuRoleAuthEntities)) {
            addRedisCache(res, String.valueOf(menuRoleAuthDto.getMenuId()));
            return CommonResult.success(res);
        }
        addRedisCache(menuRoleAuthEntities, String.valueOf(menuRoleAuthDto.getMenuId()));
        return CommonResult.success(menuRoleAuthEntities);
    }

    /**
    * @Author GroundDemo
    * @Description 添加缓存
    * @Date 12:04 2025/3/22
    * @Param [entityList, menuId]
    * @return void
    **/
    private void addRedisCache(List<MenuRoleAuthEntity> entityList, String menuId) {
        String serialize = GsonUtils.serialize(entityList);
        RedisUtils.hashSet(YWU_MENU_PERMISSION_REDIS_KEY, menuId, serialize);
        RedisUtils.setExpire(YWU_MENU_PERMISSION_REDIS_KEY, 2, TimeUnit.HOURS);
    }

    /**
     * @Author GroundDemo
     * @Description 菜单角色授权管理
     * @Date 22:12 2024/3/9
     * @Param [MenuRoleAuthPermissionDto dto]
     * @return com.ywu.common.result.CommonResult<java.lang.Object>
     **/
    public CommonResult<Object> menuRoleAuthCreateInfo(MenuRoleAuthPermissionDto permissionDto) {
        // 先删除菜单的全部权限
        List<Integer> menuIds = new ArrayList<>();
        menuIds.add(permissionDto.getMenuId());
        menuRoleAuthRepository.deleteBatchByMenuId(menuIds);
        // 删除缓存
        for (Integer menuId : menuIds) {
            RedisUtils.deleteHashKey(YWU_MENU_PERMISSION_REDIS_KEY, String.valueOf(menuId));
        }
        // 构建新的插入对象
        List<MenuRoleAuthDto> menuRoleAuthDtos = permissionDto.getMenuRoleAuthDtos();
        ArrayList<MenuRoleAuthEntity> menuRoleAuthEntities = new ArrayList<>();
        for (MenuRoleAuthDto dto : menuRoleAuthDtos) {
            MenuRoleAuthEntity menuRoleAuthEntity = new MenuRoleAuthEntity();
            YwuContext currentContext = YwuContextHolder.getCurrentContext();
            BeanUtils.copyProperties(dto, menuRoleAuthEntity);
            menuRoleAuthEntity.createInfo(currentContext.getYwuContextUser().getUserAccount());
            menuRoleAuthEntity.setId(TimerIdGenerateUtil.nextId());
            menuRoleAuthEntities.add(menuRoleAuthEntity);
        }
        if (CollectionUtils.isEmpty(menuRoleAuthEntities)) {
            return CommonResult.success(new ArrayList<>());
        }
        menuRoleAuthRepository.batchInsertMenuRoleInfo(menuRoleAuthEntities);
        return CommonResult.success(null);
    }

    /**
    * @Author GroundDemo
    * @Description 删除菜单的授权
    * @Date 19:14 2025/3/26
    * @Param [menuRoleAuthDto]
    * @return com.ywu.common.result.CommonResult<java.lang.Object>
    **/
    public CommonResult<Object> menuRoleAuthDeleteInfo(MenuRoleAuthDto menuRoleAuthDto) {
        ArrayList<Integer> menuIds = new ArrayList<>();
        menuIds.add(menuRoleAuthDto.getMenuId());
        menuRoleAuthRepository.deleteBatchByMenuId(menuIds);
        return CommonResult.success(null);
    }
}
